package com.yifeng.repo.base.utils.text;

import com.google.common.base.Splitter;
import com.yifeng.repo.base.utils.converter.JacksonHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 模版解析工具类
 * 当前仅支持类似微信模板："#交易合计：{{billCount.DATA}}笔，商家实收共{{receiptAmount.DATA}}元，商家优惠共{{discountAmount.DATA}}元";
 * Created by daibing on 2019/1/4.
 */
public class TemplateParser {

    private static final Pattern BILL_TEMPLATE_PATTERN = Pattern.compile("\\{\\{[A-Za-z0-9]+\\.DATA}}");

    public static boolean match(String template, String text) {
        Matcher matcher = BILL_TEMPLATE_PATTERN.matcher(template);
        if (matcher.find()) {
            int index = template.indexOf(matcher.group(0));
            String templateHeader = template.substring(0, index);
            String textHeader = safeCut(text, index);
            return templateHeader.equals(textHeader);
        }
        return false;
    }

    public static Map<String, Object> parseText(String template, String text) {
        List<String> templateKeys = new ArrayList<>();
        List<String> templateKeyWraps = new ArrayList<>();
        Matcher matcher = BILL_TEMPLATE_PATTERN.matcher(template);
        while (matcher.find()) {
            templateKeys.add(matcher.group(0).replace("{{", "").replace(".DATA}}", ""));
            templateKeyWraps.add(matcher.group(0));
        }

        List<String> templateFixed = listText(template, templateKeyWraps);
        List<String> values = listText(text, templateFixed);

        Map<String, Object> result = new HashMap<>();
        for (int i = 0; i < templateKeys.size(); i++) {
            result.put(templateKeys.get(i), values.get(i));
        }
        return result;
    }

    public static <T> T parseText(String template, String text, Class<T> clazz) {
        Map<String, Object> data = parseText(template, text);
        return JacksonHelper.toObj(data, clazz);
    }

    private static List<String> listText(String content, List<String> separators) {
        for (String sep : separators) {
            content = content.replace(sep, ",");
        }
        return Splitter.on(",").omitEmptyStrings().splitToList(content);
    }

    private static String safeCut(String raw, int length) {
        if (raw == null) {
            return null;
        }
        if (raw.length() <= length) {
            return raw;
        }
        return raw.substring(0, length);
    }


}
